package com.hariro.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hariro.adapter.Fragment_ShiYi_Adapter;
import com.hariro.helper.HttpURLConnHelper;
import com.hariro.helper.JsonHelper_Haming;
import com.hariro.url.NewFashionUrl;
import com.qianfeng.project.R;

public class ShiYi_Fragment extends Fragment {
	private String url_start = "http://mobileapi.j.cn/?method=dressingListv2&count=10&uid=868033010199109&freshRecord=&menuId=7&v=2.0&net=wifi";
	private String urlend = "&v=2.0&net=wifi";
	private String urlString = "";
	private ProgressDialog pDialog;
	private List<Map<String, Object>> list_fragment_shiyi;
	private Display display;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				pDialog.show();
				break;
			case 1:
				pDialog.hide();
				break;
			}
		};
	};

	private TextView textView_shiyi_title;
	private ImageView imageView_shiyi_refresh;
	private GridView gridView_fragment_shiyi;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		pDialog = new ProgressDialog(getActivity());
		// 将提示对话框的样式设置为圆形的
		pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pDialog.setMessage("数据加载中,请稍候!");
		urlString = NewFashionUrl.URL_TRY;

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// 首先加载碎片的布局
		View view = inflater.inflate(R.layout.fragment_shiyi, null);
		// 初始化试衣碎片里面的网格布局视图
		initView(view);

		return view;
	}

	private void initView(View view) {
		// 发送一个空消息显示提示对话框
		handler.sendEmptyMessage(0);

		textView_shiyi_title = (TextView) view
				.findViewById(R.id.textView_shiyi_title);
		imageView_shiyi_refresh = (ImageView) view
				.findViewById(R.id.imageView_shiyi_refresh);
		gridView_fragment_shiyi = (GridView) view
				.findViewById(R.id.gridView_fragment_shiyi);

		// 获取Display对象
		WindowManager windowManager = (WindowManager) getActivity()
				.getSystemService(Context.WINDOW_SERVICE);
		display = windowManager.getDefaultDisplay();
		Log.i("=======", "此处正常");
		// 加载网络资源并进行解析
		loadNetWorkData(urlString);
		Log.i("=======", "加载网络数据之后正常");

		// 给刷新图片按钮设置单击监听器
		imageView_shiyi_refresh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 刷新界面
				handler.sendEmptyMessage(0);
				loadNetWorkData(urlString);
			}
		});

		// 给网格布局设置条目点击监听器
		gridView_fragment_shiyi
				.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						if (list_fragment_shiyi != null
								&& list_fragment_shiyi.size() != 0) {
							String itemId = list_fragment_shiyi.get(position)
									.get("itemId").toString();
							String title = list_fragment_shiyi.get(position)
									.get("title").toString();
							FragmentTransaction transaction = getActivity()
									.getSupportFragmentManager()
									.beginTransaction();

							Fragment fragment = new ShiYi_LoadPicFragment();
							Bundle bundle = new Bundle();
							bundle.putString("itemId", itemId);

							fragment.setArguments(bundle);
							gridView_fragment_shiyi.setVisibility(View.GONE);

							transaction.replace(R.id.layout_shiyiPic, fragment,
									"200");
							textView_shiyi_title.setText(title);
							textView_shiyi_title.setPadding(30, 0, 0, 0);

							// 进入店铺后,标题属性设置可点击
							textView_shiyi_title.setClickable(true);
							// 给标题设置点击监听器
							textView_shiyi_title
									.setOnClickListener(new OnClickListener() {
										@Override
										public void onClick(View v) {
											Log.i("----->", "返回监听正常");
											textView_shiyi_title.setText("试衣");
											textView_shiyi_title
													.setClickable(false);
											textView_shiyi_title
													.setCompoundDrawables(null,
															null, null, null);
											FragmentManager manager = getFragmentManager();
											Fragment fragment = manager
													.findFragmentByTag("200");
											FragmentTransaction transaction = manager
													.beginTransaction();
											transaction.remove(fragment);// layout_newshop
											transaction.commit();
											gridView_fragment_shiyi
													.setVisibility(View.VISIBLE);
										}
									});

							Drawable drawable = getResources().getDrawable(
									R.drawable.common_back);

							// 必做的一步,否则不会显示
							drawable.setBounds(0, 0,
									drawable.getMinimumWidth(),
									drawable.getMinimumHeight());
							textView_shiyi_title.setCompoundDrawables(drawable,
									null, null, null);
							transaction.commit();
							Toast.makeText(getActivity(), itemId, 0).show();

						} else {
							Toast.makeText(getActivity(), "shiyi无数据！", 0)
									.show();
						}
					}
				});

	}

	private void loadNetWorkData(String urlString) {

		new MyTask(getActivity()).execute(urlString);

	}

	class MyTask extends AsyncTask<String, Void, String> {
		private Context context;

		public MyTask(Context context) {
			this.context = context;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			String data = new String(
					HttpURLConnHelper.loadByteFromURL(params[0]));
			if (data != null) {
				return data;
			}
			return "";
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			Log.i("网络加载下来的json字符串: ", result);

			// result就是从网络上加载下来的json字符串
			if (result != null) {
				list_fragment_shiyi = new ArrayList<Map<String, Object>>();
				list_fragment_shiyi = JsonHelper_Haming.jsonStringToList(
						result, new String[] { "shareUrl", "shareImgUrl",
								"title", "mainImgUrl", "itemId", "iconUrl" },
						"myMenuList");

				Log.i("json解析之后的结果: ", result);

				gridView_fragment_shiyi.setAdapter(new Fragment_ShiYi_Adapter(
						context, list_fragment_shiyi, display));

				handler.sendEmptyMessage(1);
			} else {
				Toast.makeText(getActivity(), "获取数据失败!", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}

}
